<?php
class TbfImage{
    //图片大小缩放,不裁剪
    //输入路径,输出路径,不会缓存
    static function ResizeFileJpeg($inPath,$outPath,$newWidth,$newHeight){
        list($width, $height) = getimagesize($inPath);
        $src = imagecreatefromjpeg($inPath);
        $dst = imagecreatetruecolor($newWidth, $newHeight);
        imagecopyresampled($dst, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
        imagejpeg($dst,$outPath);
    }

    //图片大小缩放,不裁剪
    //输入url,输出url,会缓存
    static function ResizeImageUrl($inUrl,$newWidth,$newHeight){
        $relInPath = TbfString::TrimPrefix($inUrl,TbfConfig::$UploadUrlPrefix.'/');
        if ($relInPath===false){
            throw new Exception(sprintf('[resizeImageUrl] inUrl[%s] not found upload prefix',$inUrl));
        }
        $inPath = TbfConfig::$UploadPath.'/'.$relInPath;
        if (!file_exists($inPath)){
            throw new Exception(sprintf('[resizeImageUrl] inPath[%s] file not found',$inPath));
        }
        //确定输出文件路径
        $relOutPath = $relInPath.'_cut_'.$newWidth.'x'.$newHeight.'.jpeg';
        $outPath = TbfConfig::$UploadPath.'/'.$relOutPath;
        if (file_exists($outPath)){
            return TbfConfig::$UploadUrlPrefix.'/'.$relOutPath;
        }
        TbfImage::ResizeFileJpeg($inPath,$outPath,$newWidth,$newHeight);
        return TbfConfig::$UploadUrlPrefix.'/'.$relOutPath;
    }

    //生成,并显示图片验证码.返回验证码的sha256值
    static function ImageVerify() {
        //返回验证码的sha256值
        $verify = TbfRand::SecurityLetter(4);
        $verify	= strtoupper($verify);

        //验证码
        $char_width    = imagefontwidth(5);
        $char_height   = imagefontheight(5);

        $string_width  = 15 * $char_width;
        $string_height = 3 * $char_height;

        $img_width	= $string_width  + 16;
        $img_height = $string_height + 8;
        $img = @imagecreatetruecolor($img_width, $img_height) or die("imagecreatetruecolor failed");

        // 颜色
        $background_color = imagecolorallocate($img, 238, 238, 238);

        //背景
        imagefill($img ,0, 0, $background_color);

        // 验证码
        $font = __DIR__."/Resource/arial.ttf";
        $x = 10 + mt_rand(-2, 2);
        $y = 40 + mt_rand(-2, 2);
        for($i = 0; $i < strlen($verify); $i++) {
            $text_color		  = imagecolorallocate($img, mt_rand(0,125),mt_rand(0,125),mt_rand(0,125));
            imagettftext($img,mt_rand(30,40),mt_rand(-30,30),$x,$y,$text_color,$font,substr($verify,$i,1));
            //imagestring($img, 5, $x,$y  + mt_rand(-2, 2), substr($verify, $i, 1), $text_color);
            $x += 3 * $char_width;
        }

        //header("Content-type: image/png");
        ob_start();
        imagepng($img);
        imagedestroy($img);
        $imageContent = ob_get_clean();
        return array(
            'code'=>hash('sha256',$verify),
            'imageContent'=>$imageContent,
        );
    }
}
